<?php

namespace app\api\controller;

use app\api\service\Setmeal as SetmealService;
use app\common\controller\Api;
use think\Cache;
use think\exception\ValidateException;

/**
 * 套餐接口
 */
class Setmeal extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['list', 'dishList'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = '*';
    private $setmealService;
    private $cacheName = 'setmealCache';

    public function __construct()
    {
        parent::__construct();
        $this->setmealService = new SetmealService;
    }


    /**
     * 根据分类id查询套餐
     *
     */
    public function list()
    {
        $data = $this->request->get();
        // 参数校验
        $validate  = validate('Setmeal');
        if (!$validate->scene('list')->check($data)) {
            // 抛出验证异常
            throw new ValidateException($validate->getError());
        }
        $cacheKey = $this->cacheName . $data['categoryId'];
        // 读取缓存
        $setmealCache = Cache::get($cacheKey);
        if ($setmealCache) {
            return  $this->success('返回成功', $setmealCache);
        }

        $list =  $this->setmealService->list($data);
        // 缓存数据，打上标签，方便批量删除
        Cache::tag($this->cacheName)->set($cacheKey, $list);

        return $this->success('返回成功', $list);
    }

    /**
     * 根据套餐id查询包含的菜品
     *
     * @param int $id
     */
    public function dishList($id)
    {
        // 参数校验
        $validate  = validate('Setmeal');
        if (!$validate->scene('disList')->check(['id' => $id])) {
            // 抛出验证异常
            throw new ValidateException($validate->getError());
        }
        $list =  $this->setmealService->getDishItemById($id);
        return $this->success('返回成功', $list);
    }
}
